faApp.controller('BaseCtrl',['$scope','$timeout','$interval','$location','shareService','userService','loginService','adService','sessionService','ajaxService','faService',function($scope,$timeout,$interval,$location,shareService,userService,loginService,adService,sessionService,ajaxService,faService) {  

	$scope.sysVersion = faApp.sysVersion;
	$scope.env = App.env;
  

	$scope.beforeRender = function(){
		$scope.ngViewStyle = {display:"inherit"};
	};

	$scope.showNgView = function(){
		$scope.ngViewStyle = {display:"inherit"};
	}; 

	$scope.setLogined = function(user){
		$scope.loginStatus = $scope.getCookieData("user","{}",1);
		$scope.loginStatus.loginName = user.userNickName;
		$scope.loginStatus.isLogin = true;
		$scope.loginStatus.uRole = user.uRole || "";
		$scope.loginStatus.name = user.userName;
		$scope.loginStatus.id = user.id;
		$scope.setCookieData("user",$scope.loginStatus,1);
	}; 

	$scope.logout = function(){
		$scope.loginStatus = $scope.getCookieData("user","{}",1);
		$scope.loginStatus.isLogin = false;
		$scope.loginStatus.uRole = "";
		$scope.loginStatus.id = "";
		$scope.setCookieData("user",$scope.loginStatus,1);
	};

	$scope.isLogin = function(){
		var cu = $scope.getCookieData("user","{}",1);
		return cu.isLogin;
	}; 

	$scope.updateCookie = function(user){
		$scope.loginStatus = $scope.getCookieData("user","{}",1);
		user.uRole && ($scope.loginStatus.uRole = user.uRole);
		(user.name != undefined) && ($scope.loginStatus.name = user.name);
		$scope.setCookieData("user",$scope.loginStatus,1);
	};

	$scope.setCookieData = function(k,v,mapFlag){
		$scope.setLocalCookie(k,mapFlag ? angular.toJson(v) : v);
	};

	$scope.getCookieData = function(k,v,mapFlag){
		var v = $scope.getLocalCookie(k,v);
		return mapFlag ? angular.fromJson(v) : v;
	}

	$scope.removeCookieData = function(k){
		$scope.removeLocalCookie(k);
	} 

	$scope.setLocalCookie = function(k,v,cfg){
		Cookies.set(k, v, cfg);
	};

	$scope.getLocalCookie = function(k,d){
		var v = Cookies.get(k);
		return v ? v : d;
	}

	$scope.remembermeHandler = function(model){
		if ($scope.rememberme){
			$scope.setLocalCookie('login.name', model.loginName, { expires: 86400 * 365}); // Expires in 1 years
		}else{
			$scope.setLocalCookie('login.name', "", { expires: 86400 * 365}); // Expires in 1 years
		}
	};

	$scope.checkLogin = function(){
		if (!this.isLogin()){
			this.setCookieData("lastUrl",$location.path());
			$location.path("/login");
		}
	};

	$scope.getShowName = function(){
		return this.loginStatus.name ? this.loginStatus.name : (this.loginStatus.loginName || "");
	};

	$scope.alerts = [];
	$scope.addAlert = function(text,timeout) {
		$scope.alerts.push({type : 'success',msg: text});
		$timeout(function(){
			$scope.closeAlert(0);
		},timeout || 3000000);
	};

	$scope.alertNextPage = function(text,timeout){
		shareService.set("nextAlert",text);
	}; 

	$scope.alertFromShareService = function(){
		var text = shareService.get("nextAlert");
		if (text){
			shareService.remove("nextAlert");
			var a = shareService.get("nextAlert");
			this.addAlert(text);
		}
	};

	$scope.closeAlert = function(index) {
		$scope.alerts.splice(index, 1);
	};

	$scope.toggleShow = function(el){
		var a = 1;
	};

	$scope.isCorp = function(){
		return this.loginStatus.uType == "1";
	};

	$scope.isCorpFA = function(){
		return this.loginStatus.uType == "3";
	};

	$scope.isFreeFA = function(){
		return this.loginStatus.uType == "0";
	};

	$scope.isNotAuth = function(){
		//return this.loginStatus.uRole == "1";
		return false;//20141023,不认证也可以预约
	};

	$scope.isStatusBuyable= function(product){
		return product.saleStatus != "04" && product.saleStatus !="05";
	};

	$scope.makeActualRoute = function($route){
		var rawPath = $route.originalPath || "", 
			params = $route.params || {}
			path = "",
			varName = "",
			varFlag = false,
			length = rawPath.length;

			for (var i = 0;i < length;i ++){
				var c = rawPath[i];
				if (c == ':'){
					varFlag = true;
				}else if(varFlag && c == '/'){
					path += (params[varName] || "");
					varFlag = false;
					varName = "";
				}else if(varFlag){
					varName += c;
				}else{
					path += c;
				}
			}

		if(varName) path += (params[varName] || "");
		return path;
	};


	$scope.clearFieldValidation = function(field){
		field = field || {}; 
		try{
			field.$error = {};
		}catch(e){} 
	};

	$scope.markFieldError = function(field,k){
		if (!field)return;
		$scope.clearFieldValidation(field);
		field.$valid = false;	
		field.$invalid = true;
		field.$dirty = true;	
		field.$error[k] = true;	
		return field;
	};

  $scope.historyBack = function(){
    window.history.back(-1);
  };

  $scope.onUploadFile = function(cfg){
    cfg.onReady && cfg.onReady();
    
    $timeout(function(){
      $(".add-pic-btn").each(function(){
        $.jUploader({
          button: $(this),
          action: App.apiHost + '/fileUpload.shtml?callback=angular.callback._1000&fileType=' + (cfg.type || 'advertImage')+'&refid=' + (cfg.refid || ''),
          onUpload: function (fileName) {
            cfg.onUpload && cfg.onUpload(fileName);
          },
          onComplete: function (fileName, response,id) {
            cfg.onComplete && cfg.onComplete(fileName,response,id);
          },
          onCancel: function (fileName) {
            cfg.onCancel && cfg.onCancel(fileName);
          },
          showMessage: function (message) {
            cfg.showMessage && cfg.showMessage(message);
          }
        });
      });
    },2000); 
  };

  $scope.checkLoginStatus = function(){
    loginService.loginStatus().then(function(json){
      if (!json.loginStatus){
        $location.path("/login");
      }    
    });
  };

  $scope.setNavModule = function(v){
    $scope.nav.module = v;
  };
// 新增product.status == 4  金融产品内部审核中   写死的方旭id审核
  $scope.isPassVerifyable4 = function(product){
    product = product || {};
    var s = (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 4);
    return s&&($scope.loginStatus.loginName=='方旭'||$scope.loginStatus.loginName=='admin');
  };

  $scope.isPassVerifyable = function(product){
    product = product || {};
    return (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 1||product.status == 6);
  };

// 新增product.status == 5 发布审核中    写死的李总id审核
 $scope.isPassPublishable5 = function(product){
    product = product || {};
    var s = (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 5);
    return s&&($scope.loginStatus.loginName=='李宏彪'||$scope.loginStatus.loginName=='admin');
  };

  $scope.isPassPublishable = function(product){
    product = product || {};
    return (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 2);
  };

  $scope.isStopable = function(product){
    product = product || {};
    return (product.pPublicStatus == 2);
  };

  $scope.isPassEstablishable = function(product){
    product = product || {};
    return (product.pPublicStatus == 2 && !product.pEstablishmentTime);
  };

  $scope.isDeleteable = function(product){
    product = product || {};
    return (product.pPublicStatus == 1);
  };

  $scope.hasAuth = function(where,who){
    var _access = sessionService.getItem("user.access",""),authFlag = false;
    if (_access == "all"){
      return true;
    }
    angular.forEach(who.split(","),function(o){
      var realUrl = ajaxService.getApiUri(o);
          urlPaths = realUrl.split("/"),
          lastUrlPath = urlPaths[urlPaths.length - 1];
          if (_access.indexOf(lastUrlPath) != -1){
            authFlag = true 
          }
    });
    return authFlag;
  };

  $scope.checkBrowserEnv = function(){
    $scope.envIsOk = true;
    $scope.envMap = {};
    if (!window.sessionStorage){
      $scope.envIsOk = false;
    }
    if (window.attachEvent){
      $scope.envMap['isIE'] = true;
    }
  };
  
  
  $scope.watchIsChange = function(){
    $scope.lastConfig = $scope.lastConfig || {};
    $scope.config = $scope.config || {};
    delete $scope.lastConfig.callback;
    delete $scope.config.callback;
    var last = angular.toJson($scope.lastConfig);
    var now = angular.toJson($scope.config);
    //// console.log(last);
    //// console.log(now);
    if (last != now){
      $scope.lastConfig = App.cloneJson($scope.config);
      return true;
    }else{
      return false;
    };
  };

   //huqy   机构筛选
  $scope.sfCompanyList = {};
  $scope.isShowSelectCompany = false;
  $scope.isNewCompany = false;
  $scope.newCompanyName = '';
  $scope.showJigouCompany = function(name){
    console.log(name);
    $scope.isNewCompany = false;
    if(name){
      // 根据name查询列表
      //if(name.length >= 2){
        //$scope.isShowSelectCompany = true;
        faService.jigouQuery({'investOwnerName': name}).then(function(json){
          $scope.sfCompanyList = json.list;
          if(json && $scope.sfCompanyList.length <= 0){
            $scope.isNewCompany = true;
            $scope.newCompanyName = name;
            $scope.isShowSelectCompany = false;
          }else{
            $scope.isShowSelectCompany = true;
          }
        });
      //}
    }else{
      $scope.isShowSelectCompany = false;
    }

  }

  $scope.keyupChange=function(e,v){
    console.log(e);
    //空格键、回车键、1-9键盘  直接进行调用
    if(e.keyCode==32 || e.keyCode==13 || (e.keyCode>=49 && e.key<=53)){
      if(v=='ac'){
        //供应方
        $scope.queryAccessCompany=$('#queryAccessCompany').val();
      }else if(v=='ucn'){
        //三方机构   白名单公司
        $scope.uCompanyName=$('#uCompanyName').val();
        $scope.showSanfangCompany($scope.uCompanyName);
      }else{
        //机构
       $scope.product.pInvestOwner=$('#pInvestOwner').val();
       $scope.showJigouCompany($scope.product.pInvestOwner);
      }
    }
  }
  $scope.selectedJigouCompany = function(name){
    $scope.isShowSelectCompany = false;
    $scope.product.pInvestOwner = name;
  }
  
  ///////机构

//全局打开table页面
  $scope.changeClickNone = function(datauri,dataid,name){
    var x=top.document.getElementById('noneclick');
    $(x).attr('data-id',dataid);
    $(x).attr('data-uri',datauri);
     $(x).text(name);
    top.document.getElementById('noneclick').click();
  }

	$scope.sexMapModel = [ { value:1,text:"男"}, { value:2,text:"女"}, { value:3,text:"保密"}, ]; 
	$scope.payStatusMapModel = [ { value:1,text:"预约"}, { value:2,text:"签约"}, { value:3,text:"返佣"}, ];
	$scope.productLevelMapModel = [ { value:'01',text:"AAA"}, { value:'02',text:"AA"}, { value:'03',text:"A"}, { value:'04',text:"BBB"}, { value:'05',text:"BB"}, { value:'06',text:"B"}, { value:'07',text:"CCC"}, { value:'08',text:"CC"}, { value:'09',text:"C"}, { value:'10',text:"D"} ];
	$scope.newsTypeMapModel = App.newsTypeMapModel;
	$scope.publicAreaModel = App.publicAreaModel;
	$scope.paymentInterestTypeModel = App.paymentInterestTypeModel;
	$scope.investTypeModel = App.investTypeModel;
	$scope.pLevelModel = App.pLevelModel;
	$scope.advertPositionModel = App.advertPositionModel;
	$scope.productStatusModel = App.productStatusModel;
	$scope.productPublicStatusModel = App.productPublicStatusModel;
	$scope.productTypeModel = App.productTypeModel;
  $scope.dictMap = App.dictMap;

	$scope.globalSetting = App.globalSetting;
	$scope.loginStatus = $scope.getCookieData("user","{}",1); 

	$scope.apiHost = App.apiHost;
	$scope.staticHost = App.staticHost;

	$scope.alertFromShareService();

}]);
faApp.controller('BaseListCtrl',['$scope','$controller','sessionService','$timeout',function($scope,$controller,sessionService,$timeout) {  
  
	$controller('BaseCtrl', {$scope: $scope}); 

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
	};

  $scope.searchMap = {};
  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });
    $scope.config.pageNo = 1;
    console.log($scope.config);

    !notsave && $scope.saveLastSearchConfig();
  };
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
    $timeout(function() {
      $(window).scrollTop(0);
    }, 200);
	}; 
  
  $scope.getLastSearchConfig = function(){
    var cfgStr = sessionService.getItem($scope.getLastSearchConfigKey(),"{}");
    $scope.searchMap = angular.fromJson(cfgStr);
    /*$scope.clearLastSearchConfig();*/
  };
  
  $scope.saveLastSearchConfig = function(){
    sessionService.setItem($scope.getLastSearchConfigKey(),angular.toJson($scope.searchMap));
  };
  
  $scope.clearLastSearchConfig = function(){
    sessionService.removeItem($scope.getLastSearchConfigKey());
  };
  
  $scope.getLastSearchConfigKey = function(){
    return "cfg_" + $scope.getCtrlName();
  };
  
  $scope.getCtrlName = function(){
    $scope.ctrlName = $scope.ctrlName || ((new Date()).getTime() + "");
    return $scope.ctrlName;
  };
  
  $scope.getLastSearchConfig();
  $scope.search(1);
 
}]);

